const {exec} = require("../db/mysql");
const xss = require('xss');
const getList = (author,keyword)=>{
    //  let sql = `select * from blogs where author='${author}' and title='${keyword}'`;
    let sql = 'select * from blogs where 1=1 '
     if(author){
         sql += `and author ='${author}' `
     }
     if(keyword){
         sql += `and title like '%${keyword}%' `
     }
     sql += "order by id desc;"

     return exec(sql);
}
//获取博客详情
const getDetail = (id) => {
    let sql = `select * from blogs where id=${id}`;
    return exec(sql).then(rows=>{
        return rows[0];
    });
}
//新建博客
const newBlog = (blogData = {})=>{
    blogData.title = xss(blogData.title);
    // console.log('canshu',blogData);
    let sql = `insert into blogs(title,content,createtime,author)values('${blogData.title}','${blogData.content}','${blogData.createtime}','${blogData.author}');`;
    return exec(sql).then(data=>{
        return data.insertId;
    });
}
//更新博客
const updateBlog = (id,blogData={})=>{
    //id就是要跟新博客的id
    //blogData是一个博客对象，包含title content属性
    let sql = `update blogs set content='${blogData.content}',title='${blogData.title}' where id='${id}'`;
    return exec(sql).then(result=>{
        
        if(result.affectedRows){
            return {change: true};
        }
      
    })
}
const delBlog = (id,author)=>{
    //id就是要删除博客的id
   
   let sql = `delete from blogs where id=${id*1} and author='${author}';`;
   
   return exec(sql).then(result=>{
       return 1
   })
}
module.exports = 
    {
        getList,
        getDetail ,
        newBlog,
        updateBlog,
        delBlog
    }